<template>
  <div class="edit_process_list">
    <div class="edit_process_list_btn_box">
      <el-button type="primary" class="primary_btn" @click="saveProcess">{{$t('public.save')}}</el-button>
      <!--<el-button type="primary" class="primary_btn" @click="reloadProcess">生效</el-button>-->
      <!--<el-button type="primary" v-if="processObj._id" class="primary_btn edit_process_list_delete_btn delete_btn" @click="delProcess">{{$t('public.delete')}}</el-button>-->
    </div>
    <el-form class="process_edit_form" :model="processObj" label-width="90px" ref="currentProcess" :rules="rules">
      <el-form-item class="edit_process_list_mail_form_li" prop="name" :label="$t('channelsettings.process2')+':'">
        <el-input v-model.trim="processObj.name" class="edit_process_list_input_box"></el-input>
      </el-form-item>
      <br/>
      <el-form-item class="edit_process_list_mail_form_li"  prop="firstNodeId" :label="$t('channelsettings.process6')+':'">
        <el-select class="edit_process_list_input_box" @change="nodeIdChange" v-model="processObj.firstNodeId" :placeholder="$t('configLazyLoad.process.processTip1')">
          <el-option
            v-for="item in options"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="flowError" class="flowError font12">
      {{$t('configLazyLoad.process.processTip2')}}
    </div>
    <div v-if="chartError" class="error font16">
      {{$t('configLazyLoad.process.processTip3')}}
    </div>
    <div class="svgContainer Horizontal">
      <div id="webchat_pricess_id" style="overflow: scroll;"></div>
    </div>
  </div>
</template>
<script>
  import search from '../../base/search.vue'
  import mermaid from 'mermaid'
//  import 'mermaid/dist/mermaid.forest.css'
  import * as types from '@modules/config/channelConfig/webchatSchdule/mutation-types.js'
  import { deepClone } from '@utils/m7Utils.js'
  export default{
    name: 'processManagementEdit',
    data () {
      let self = this
      window.WebchatNodeClick = function (item) {
        let id = this.id
        self.handlerNodeClick(id)
      }
      return {
        currentPage: 1,
        count: 0,
        pageSize: 10,
        rules: {
          name: [
            { required: true, message: this.$t('configLazyLoad.process.processTip4'), trigger: 'blur' }
          ],
          firstNodeId: [
            { required: true, message: this.$t('configLazyLoad.process.processTip1'), trigger: 'change' }
          ]
        },
        defaultList: [
          {
            name: this.$t('configLazyLoad.process.endNode'),
            _id: 'finish',
            type: 'system'
          }, {
            name: this.$t('configLazyLoad.process.queuingNode'),
            _id: 'queue',
            type: 'system'
          }
        ],
        extenNodeType: [
          {
            key: 'agentBusyProcessTo',
            status: this.$t('configLazyLoad.process.processStatus1')
          }, {
            key: 'agentOfflineProcessTo',
            status: this.$t('configLazyLoad.process.processStatus2')
          }, {
            key: 'agentStatusCloseProcessTo',
            status: this.$t('configLazyLoad.process.processStatus3')
          }, {
            key: 'extenNotMatchProcessTo',
            status: this.$t('configLazyLoad.process.processStatus4')
          }, {
            key: 'noExtenProcessTo',
            status: this.$t('configLazyLoad.process.processStatus5')
          }],
        queueNodeType: [{
          key: 'agentOfflineProcessTo',
          status: this.$t('configLazyLoad.process.processStatus2')
        }, {
          key: 'queueEmptyProcessTo',
          status: this.$t('configLazyLoad.process.processStatus6')
        }, {
          key: 'queueNumReachProcessTo',
          status: this.$t('configLazyLoad.process.processStatus7')
        }],
        robotNodeType: [{
          key: 'commonProcessTo',
          status: this.$t('configLazyLoad.process.processStatus8')
        }, {
          key: 'wechatProcessTo',
          status: this.$t('configLazyLoad.process.processStatus9')
        }, {
          key: 'weiboProcessTo',
          status: this.$t('configLazyLoad.process.processStatus10')
        }],
        text: '',
        currentBusiness: {},
        chartError: false,
        processObj: {
          _id: '',
          account: '', // 账户id
          name: '', // 名称
          firstNodeType: 'entrance', // 开始节点类型
          firstNodeAccessType: '',
          firstNodeId: '', // 开始节点id
          createTime: '', // 创建时间
          createUser: '', // 创建人
          updateTime: '', // 修改时间
          updateUser: ''
        },
        flowArray: [],
        flowError: false // 图表绘制中出现错误
      }
    },
    props: {
      random: {type: Number},
      editRandom: {type: Number}
    },
    methods: {
      parseData () {
        this.chartError = false
        this.flowError = false
        this.flowArray = []
        this.text = 'graph LR; \n '
        if (document.getElementById('webchat_pricess_id')) {
          document.getElementById('webchat_pricess_id').innerHTML = ''
          if (document.getElementById('did1')) {
            let did1 = document.getElementById('did1')
            did1.parentNode.removeChild(did1)
          }
        }
        let entranceNode = this.allNodeList.find((item) => { return item._id === this.processObj.firstNodeId })
        if (!entranceNode) {
          return
        }
        if (entranceNode.welcomeNodeId) {
          let welcomeNode = this.allNodeList.find((item) => { return item._id === entranceNode.welcomeNodeId })
          let welcomeNodeId = entranceNode._id + '#' + welcomeNode._id
          let code = entranceNode._id + '["' + entranceNode.name + '"] -->' + welcomeNodeId + '("' + welcomeNode.name + '"); \n'
          if (this.text.indexOf(code) === -1) {
            this.text += code
          }
        }
        if (entranceNode.accessType === 'wechat' || entranceNode.accessType === 'weibo' || entranceNode.accessType === 'wxmini') {
          let nextNode = this.allNodeList.find((node) => { return node._id === entranceNode.processTo })
          if (nextNode) {
            this.concatCode(entranceNode, nextNode, '', 'welcome')
            try {
              this.analyCode(nextNode)
            } catch (err) {
              console.log(err)
            }
          }
        } else if ((entranceNode.accessType === 'common' || entranceNode.accessType === 'sdk') && entranceNode.entrances && entranceNode.entrances.length > 0) {
          entranceNode.entrances.forEach((entry) => {
            if (entry.welcomeNodeId) {
              let welcomeNode = this.allNodeList.find((item) => { return item._id === entry.welcomeNodeId })
              let welcomeNodeId = entry._id + '#' + welcomeNode._id
              this.text += entranceNode._id + '["' + entranceNode.name + '"] -->' + entry._id + '("' + entry.name + '"); \n'
              this.text += entry._id + '["' + entry.name + '"] -->' + welcomeNodeId + '("' + welcomeNode.name + '"); \n'
              this.text += 'click ' + entranceNode._id + ' WebchatNodeClick; \n'
              this.text += 'click ' + welcomeNodeId + ' WebchatNodeClick; \n'
              this.text += 'click ' + entry._id + ' WebchatNodeClick; \n'
            } else {
              this.text += entranceNode._id + '["' + entranceNode.name + '"] -->' + entry._id + '("' + entry.name + '"); \n'
              this.text += 'click ' + entranceNode._id + ' WebchatNodeClick; \n'
              this.text += 'click ' + entry._id + ' WebchatNodeClick; \n'
            }
            try {
              this.analyCode(entry)
            } catch (err) {
              console.log(err)
            }
          })
        }
        console.log(this.text)
        let mermaidholder = document.getElementById('webchat_pricess_id')
        mermaidholder.innerHTML = this.text
        mermaidholder.removeAttribute('data-processed')
        mermaid.init('#webchat_pricess_id')
        mermaidholder.firstChild.style.height = mermaidholder.firstChild.getAttribute('viewBox').split(' ')[3] + 'px'
        mermaidholder.firstChild.style.width = mermaidholder.firstChild.getAttribute('viewBox').split(' ')[2] + 'px'
        mermaidholder.style.overflow = 'auto'
        let nodeArray = document.querySelectorAll('#webchat_pricess_id g.nodes g.node')
        if (nodeArray.length > 0) {
          nodeArray.forEach((item) => {
            item.addEventListener('click', window.WebchatNodeClick, false)
          })
        } else {
          this.chartError = true
        }
      },
      analyCode (item) {
        if (item.type === 'system' || item.type === 'leavemsg') {
          return
        }
        if (item.welcomeNodeId) {
          let welcomeNode = this.allNodeList.find((item1) => { return item1._id === item.welcomeNodeId })
          let welcomeNodeId = item._id + '#' + welcomeNode._id
          let code = item._id + '["' + item.name + '"] -->' + welcomeNodeId + '("' + welcomeNode.name + '"); \n'
          if (this.text.indexOf(code) === -1) {
            this.text += code
          }
        }
        if (!item.type) {
          if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
              this.text += item._id + '["' + item.name + '"] -->' + child._id + '("' + child.name + '"); \n'
              this.analyCode(child)
            })
          } else if (item.processTo) {
            let nextNode = this.allNodeList.find((node) => { return node._id === item.processTo })
            if (nextNode) {
              if (this.concatCode(item, nextNode, '', 'welcome')) {
                this.analyCode(nextNode)
              }
            }
          }
        } else if (item.type === 'exten') {
          this.extenNodeType.forEach((type) => {
            let nextNode = this.allNodeList.find((node) => { return node._id === item[type.key] })
            if (nextNode) {
              if (this.concatCode(item, nextNode, type.status, 'welcome')) {
                this.analyCode(nextNode)
              }
            }
          })
        } else if (item.type === 'queue') {
          this.queueNodeType.forEach((type) => {
            let nextNode = this.allNodeList.find((node) => { return node._id === item[type.key] })
            if (nextNode) {
              if (this.concatCode(item, nextNode, type.status, 'welcome')) {
                this.analyCode(nextNode)
              }
            }
          })
        } else if (item.type === 'robot') {
          this.robotNodeType.forEach((type) => {
            let nextNode = this.allNodeList.find((node) => { return node._id === item[type.key] })
            if (nextNode) {
              if (this.concatCode(item, nextNode, type.status, 'welcome')) {
                this.analyCode(nextNode)
              }
            }
          })
        } else if (item.type === 'time') {
          item.dates && item.dates.length > 0 && item.dates.forEach((date) => {
            let nextNode = this.allNodeList.find((node) => { return node._id === date.processTo })
            if (nextNode) {
              if (this.concatCode(item, nextNode, '', 'welcome')) {
                this.analyCode(nextNode)
              }
            }
          })
          let nextNode = this.allNodeList.find((node) => { return node._id === item.unmatchProcessTo })
          if (nextNode) {
            if (this.concatCode(item, nextNode, this.$t('configLazyLoad.process.otherTime'), 'welcome')) {
              this.analyCode(nextNode)
            }
          }
        }
      },
      concatCode (prev, next, status, welcome) {
        let code, prevId, prevName
        if (welcome && prev.welcomeNodeId) {
          prevId = prev._id + '#' + prev.welcomeNodeId
          let welcomeNode = this.allNodeList.find((node) => { return node._id === prev.welcomeNodeId })
          prevName = welcomeNode.name
        } else {
          prevId = prev._id
          prevName = prev.name
        }
        if (status) {
          code = prevId + '("' + prevName + '")' + '-->' + '|' + status + '|' + next._id + '("' + next.name + '"); \n'
        } else {
          code = prevId + '("' + prevName + '")' + '-->' + next._id + '("' + next.name + '"); \n'
        }
        if (this.text.indexOf(code) === -1) {
          this.text += code
        }
        if (this.flowArray.indexOf(next._id + prevId + '') !== -1) {
          this.flowError = true
          if (this.text.indexOf('class ' + prevId + ' webchatFlowError; \n') === -1) {
            this.text += 'class ' + prevId + ' webchatFlowError; \n'
          }
          if (this.text.indexOf('class ' + next._id + ' webchatFlowError; \n') === -1) {
            this.text += 'class ' + next._id + ' webchatFlowError; \n'
          }
          return false
        } else {
          this.flowArray.push(prevId + next._id + '')
//          this.flowArray.push(next._id + prev._id + '')
          return true
        }
      },
      handlerNodeClick (id) {
        let currentId
        if (id.indexOf('#') > -1) {
          currentId = id.split('#')[1]
        } else {
          currentId = id
        }
        let node = this.allNodeList.find((node) => { return node._id === currentId })
        console.log(node)
        if (node && node.type !== 'system') {
          this.$emit('nodeEditFun', node)
        }
      },
      nodeIdChange (data) {
        let dataObj = deepClone(this.$store.state.config.channelConfig.webchatSchdule.currentEditProcess)
        dataObj.firstNodeId = data
        dataObj.name = this.processObj.name
//        let allEntranceNode = this.$store.state.config.channelConfig.webchatSchdule.entranceNode
//        allEntranceNode.forEach((item) => {
//          if (item._id === data) {
//            dataObj.firstNodeAccessType = item.accessType
//          }
//        })
        this.$store.commit(types.SET_CURRENT_PROCESS_EDIT, {data: dataObj})
        this.parseData()
      },
      resetForm () {
        this.$refs['currentProcess'].resetFields()
        this.processObj = this.currentProcess
        this.parseData()
      },
      parseProcess () {
        this.processObj = this.currentProcess
        this.parseData()
      },
      saveProcess () {
        let that = this
        this.$refs['currentProcess'].validate((valid) => {
          if (valid) {
            let allEntranceNode = this.$store.state.config.channelConfig.webchatSchdule.entranceNode
            allEntranceNode.forEach((item) => {
              if (item._id === that.processObj.firstNodeId) {
                that.processObj.firstNodeAccessType = item.accessType
              }
            })
            if (!that.processObj._id) {
              that.$store.dispatch('addProcess', that.processObj).then((res) => {
                if (res.success) {
                  that.$message.success(this.$t('config.customer.addSucc'))
                  that.$emit('back', 'add')
                }
              })
            } else {
              that.$store.dispatch('updateProcess', that.processObj).then((res) => {
                if (res.success) {
                  that.$message.success(this.$t('configLazyLoad.public.editSuccess'))
                  that.$emit('back', 'edit')
                }
              })
            }
          }
        })
      },
      reloadProcess () {
        this.$store.dispatch('reloadProcess', {}).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('configLazyLoad.process.effectiveSuccessfully'))
            this.$emit('back')
          } else {
            this.$message.error(this.$t('configLazyLoad.process.effectiveFail'))
          }
        })
      }
    },
    watch: {
      random () {
        this.resetForm()
      },
      editRandom () {
        this.parseProcess()
      },
      currentProcess () {
        this.processObj = this.currentProcess
      }
    },
    computed: {
      currentProcess () {
        return deepClone(this.$store.state.config.channelConfig.webchatSchdule.currentEditProcess)
      },
      allNodeList () {
        let arr = []
        let allList = this.$store.state.config.channelConfig.webchatSchdule.webchatSchNodeList
        arr = this.defaultList.concat(allList)
        return arr
      },
      options () {
        let arr = []
        this.allNodeList.forEach((item) => {
          if (item.type === 'entrance') {
            arr.push(item)
          }
        })
        let arrNew = arr.map(li => ({ label: li.name, value: li._id }))
        if (this.processObj.firstNodeId) {
          let flag = false
          arrNew.forEach((item) => {
            if (item.value === this.processObj.firstNodeId) {
              flag = true
            }
          })
          if (!flag) {
            this.processObj.firstNodeId = ''
          }
        }
        return arrNew
      }
    },
    mounted () {
      this.processObj = this.currentProcess
      this.parseData()
    },
    beforeMount () {
      this.processObj = this.currentProcess
//      this.resetForm()
    },
    components: {
      search
    }
  }
</script>
<style lang="stylus">
  @import "../../../../../../assets/common.styl"
  .edit_process_list
    .error
      text-align center
      padding-top: 100px;
    .svgContainer
      height: calc(100vh - 350px);
      width: 100%;
      text-align center
    .flowError
      text-align center
      color $c-prompt
  #webchat_pricess_id
    margin 0 auto
  /*工单配置&&通话配置流程图自定义样式*/
  #webchat_pricess_id .nodes .node rect,#mermaidholder .nodes .node rect,#mermaidholder .node circle, #mermaidholder .node ellipse, #mermaidholder .node polygon, #mermaidholderpop .nodes .node rect,#mermaidholderpop .node circle, #mermaidholderpop .node ellipse, #mermaidholderpop .node polygon{
    fill: rgba(245,245,245,0) !important;
    color: $cf-gray0;
    stroke:  #A6A6A6;
    cursor: pointer;
  }
  #webchat_pricess_id g.nodes :hover > g.label {
    color: $c-main;
  }
  #webchat_pricess_id g.nodes .webchatFlowError:hover > rect {
    stroke: red !important
    fill black
  }
  #webchat_pricess_id g.nodes :hover > rect {
    stroke: $c-main !important;
  }
  #webchat_pricess_id .webchatFlowError rect{
    stroke: red !important
  }
  #webchat_pricess_id .webchatFlowError g.label{
    color: red !important
  }
  #webchat_pricess_id g.nodes.webchatFlowError :hover > g.label {
    stroke: red !important
  }
  #webchat_pricess_id .edgeLabel {
    background #fff !important
  }
  /*#webchat_pricess_id .nodes .node g.label:hover{*/
  /*color: #1abb9e;*/
  /*}*/
  #webchat_pricess_id .nodes .node g.label {
    cursor: pointer;
  }
  #webchat_pricess_id .edgePaths .edgePath path, #mermaidholder .edgePaths .edgePath path,#mermaidholderpop .edgePaths .edgePath path{
    stroke: #a6a6a6 !important;
  }
  #webchat_pricess_id .edgePaths .edgePath marker path, #mermaidholder .edgePaths .edgePath marker path, #mermaidholderpop .edgePaths .edgePath marker path{
    fill: #a6a6a6 !important;
  }
  #webchat_pricess_idrect{
    fill: rgba(245,245,245,0) !important;
    stroke-opacity: 0;
  }
  #mermaidholder .edgeLabel,#mermaidholderpop .edgeLabel{
    color: $c-main
  }
  .edit_process_list_delete_btn
    background-color #ff6b6b
    border-color #ff6b6b
  .edit_process_list
    padding 10px
  .edit_process_list_mail_form_li
    width 480px
    display inline-block
  .process_edit_form
    text-align center
    margin-top 10px
  .edit_process_list_input_box
    width calc(100% - 90px)
  .edit_process_list_btn_box
    text-align right
</style>
